package com.persondemo.videoappliction.ui.image;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.ImageViewState;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.persondemo.videoappliction.R;
import com.persondemo.videoappliction.component.ApplicationComponent;
import com.persondemo.videoappliction.ui.base.BaseActivity;
import com.persondemo.videoappliction.utils.ImageLoaderUtil;
import com.persondemo.videoappliction.utils.T;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;


/**
 * Created by Administrator on 2018/4/19.
 */

public class ImageDetailsActivity extends Activity implements ViewPager.OnPageChangeListener, View.OnTouchListener {
    /**
     * 用于管理图片的滑动
     */
    private ViewPager viewPager;

    /**
     * 显示当前图片的页数
     */
    private TextView pageText;
    ArrayList<String> list;
    int imagePosition;
    String find;
    private long downTime;

    // 记录开始手指点击的位置,和滑动的X距离
    private int StartX;
    private static final int SAVE_SUCCESS = 0;//保存图片成功
    private static final int SAVE_FAILURE = 1;//保存图片失败
    private static final int SAVE_BEGIN = 2;//开始保存图片
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SAVE_BEGIN:
                    T.showShort(ImageDetailsActivity.this, "开始保存图片...,请勿继续点击！");
                    break;
                case SAVE_SUCCESS:
                    T.showShort(ImageDetailsActivity.this, "图片保存成功,请到相册查找");

                    break;
                case SAVE_FAILURE:
                    T.showShort(ImageDetailsActivity.this, "图片保存失败,请稍后再试...");

                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.image_details);
        T.showShort(ImageDetailsActivity.this, "长按点击可保存图片！");
        list = getIntent().getStringArrayListExtra("list_img");
        imagePosition = getIntent().getIntExtra("image_position", 0);
        find = getIntent().getStringExtra("type");//这个find只是一个标识服，只有从发现页面跳转过来才有find数据
        pageText = findViewById(R.id.page_text);
        if (find == "" || find == null || find.equals("")) {
            pageText.setText((imagePosition + 1) + "/" + (list.size()));
        } else {
            pageText.setText((imagePosition) + "/" + (list.size()));
        }
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        ViewPagerAdapter adapter = new ViewPagerAdapter();
        viewPager.setAdapter(adapter);
        viewPager.setOnTouchListener(this);// 为ViewPager设置ontouch监听获取滚动距离
        if (find == "" || find == null || find.equals("")) {
            viewPager.setCurrentItem(imagePosition);
        } else {
            viewPager.setCurrentItem(imagePosition - 1);
        }
        viewPager.setOnPageChangeListener(this);
//		viewPager.setEnabled(false);
        // 设定当前的页数和总页数

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:

                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        super.dispatchTouchEvent(ev);
        switch (ev.getAction()) {
            // 记录用户手指点击的位置
            case MotionEvent.ACTION_DOWN:
                StartX = (int) ev.getX();
                downTime = System.currentTimeMillis();
                break;
            case MotionEvent.ACTION_UP:
                if (System.currentTimeMillis() - downTime < 100
                        && Math.abs(StartX - ev.getX()) < 30) {
                    finish();
                }
                break;
        }
        return false;// return false,继续向下传递，return true;拦截,不向下传递
    }

    /**
     * ViewPager的适配器
     *
     * @author guolin
     */
    class ViewPagerAdapter extends PagerAdapter {
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = LayoutInflater.from(ImageDetailsActivity.this).inflate(
                    R.layout.photoview, null);
            final SubsamplingScaleImageView largeImageView = view.findViewById(R.id.zoom_image_view);
            ImageView imageView = view.findViewById(R.id.gif_view);
            //长按保存图片到相册
            largeImageView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    showpop(position);
                    return false;
                }
            });
            largeImageView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CUSTOM);
            largeImageView.setMinScale(1.0F);//最小显示比例
            largeImageView.setMaxScale(10.0F);//最大显示比例（太大了图片显示会失真，因为一般微博长图的宽度不会太宽）
            if (list.get(position).contains(".gif")) {
                imageView.setVisibility(View.VISIBLE);
                largeImageView.setVisibility(View.GONE);
                ImageLoaderUtil.LoadImage(ImageDetailsActivity.this, list.get(position), imageView);
            }
            Glide.with(ImageDetailsActivity.this).load(list.get(position)).downloadOnly(new SimpleTarget<File>() {
                @Override
                public void onResourceReady(File resource, Transition<? super File> transition) {
                    // 将保存的图片地址给SubsamplingScaleImageView,这里注意设置ImageViewState设置初始显示比例
                    largeImageView.setImage(ImageSource.uri(Uri.fromFile(resource)), new ImageViewState(2.0F, new PointF(0, 0), 0));
                }
            });

            ViewParent viewParent = view.getParent();
            if (viewParent != null) {
                ViewGroup parent = (ViewGroup) viewParent;
                parent.removeView(view);
            }
            container.addView(view);
            return view;
        }

        private void showpop(int postion) {
            AlertDialog.Builder builder = new AlertDialog.Builder(ImageDetailsActivity.this);
            final AlertDialog dialog;
            View dialgview = LayoutInflater.from(ImageDetailsActivity.this).inflate(R.layout.item_delte, null, false);
            TextView delte_title = dialgview.findViewById(R.id.delte_title);
            TextView delte_comment = dialgview.findViewById(R.id.delte_comment);
            delte_title.setText("保存");
            delte_comment.setText("是否保存图片到相册！");
            dialog = builder.setView(dialgview).create();
            if (dialog.isShowing()) {
                dialog.dismiss();
            } else {
                dialog.show();
            }
            dialgview.findViewById(R.id.dilog_nickname_reset_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dialog.isShowing()) {
                        dialog.dismiss();
                    }
                }
            });
            dialgview.findViewById(R.id.dilog_nickname_reset_comfrim).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //保存图片必须在子线程中操作，是耗时操作
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            mHandler.obtainMessage(SAVE_BEGIN).sendToTarget();
                            Bitmap bp = returnBitMap(list.get(postion));
                            saveImageToPhotos(ImageDetailsActivity.this, bp);
                        }
                    }).start();
                    dialog.dismiss();
                }
            });
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
        }
    }


    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @Override
    public void onPageSelected(int currentPage) {


        // 每当页数发生改变时重新设定一遍当前的页数和总页数
        pageText.setText((currentPage + 1) + "/" + (list.size()));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    /**
     * 将URL转化成bitmap形式
     *
     * @param url
     * @return bitmap type
     */
    public final static Bitmap returnBitMap(String url) {
        URL myFileUrl;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
            HttpURLConnection conn;
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 保存图片到本地相册
     */
    private void saveImageToPhotos(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mHandler.obtainMessage(SAVE_FAILURE).sendToTarget();
            return;
        }
        // 最后通知图库更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);
        mHandler.obtainMessage(SAVE_SUCCESS).sendToTarget();
    }
}
